<?php

/**
 * @author chenshubo
 * 菜鸟
 */
namespace App\Service\OrderService\OrderRouteService;
use App\Model\CommodityModel\SupplierCommodity;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Model\CommodityModel\SupplierCompany;
use App\Model\PssModel\PddToken;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Model\CommodityModel\WarehouseInfo;
use App\Service\VendorClient\ShopCaiNiao\ShopPddOrderSendCaiNiaoSupplierApiClient;
use App\Service\VendorClient\ShopCaiNiao\ShopCaiNiaoApiClient;
use App\Service\VendorClient\ShopGwApi\ShopPddUserSpecialGwApiClient;

class Shopcainiao extends BaseSupplierRouterService
{
    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        //下单商品重组
        $supplierGoodsInfo  = $param['supplierGoodsInfo'];
        $userGoodsList      = $supplierGoodsInfo['userGoodsList'];
        $goodsList          = $supplierGoodsInfo['goodsList'];
        $orderItems = [];

        //根据defaultStock分组
        $defaultStockGroupGoodsList = [];
        foreach ($goodsList as $item ) {
            $defaultStockGroupGoodsList[$item['defaultStock']][] = $item;
            unset($item);
        }

        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
            ) ? true : false;

        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false ;

        //按照上游仓库进行拆单
        foreach ($defaultStockGroupGoodsList as $item )
        {
            //重新合并每一个仓库商品
            $orderGoods = [];
            foreach ($item as $goods ) {
                $orderGoods = array_merge($orderGoods,$userGoodsList[$goods['skuCode']]);
                unset($goods);
            }

            //生成供应商主单号
            $supplierCode = $param['supplierGoodsInfo']['supplierCode'];
            $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
            $param['order']['supplier_csn'] = IdService::instance()->getOtherID();
            //下游已申报，则使用下游的订单号作为中台子单号
            if( $isDelare && !$isShop ) {
                $param['order']['supplier_dsn'] = $param['order']['orderSn'];
            } else {
                $param['order']['supplier_dsn'] = IdService::instance()->getOtherID();
            }

            $param['order']['goods'] = $orderGoods;
            $res = OrderSupplier::instance()->getSupplierCreateOrderData($param);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }

            $orderItems[] = $res['data'];
        }

        return Normal::returnCode(Normal::SUC,"获取成功",[
            'supplierCode' => $supplierCode,
            'orderItems' => $orderItems
        ]);
    }

    /**
     * 订单申报
     * @param array $param
     * @return mixed
     */
    public function orderPay( $param = [] )
    {
        $binfo = $param['binfo'];
        if( $binfo['user_tag'] == self::PDD_USER_TAG ) {
            //拼多多专用
            $supplierOrder  = $param['supplierOrder'];
            $pddToken = PddToken::instance()->info(['bid'=>$supplierOrder['bid']]);
            if( empty($pddToken['extends']) ) {
                return Normal::returnCode(Normal::FAIL,"拼多多授权参数未配置,请核对！");
            }

            $param['PddExtends'] = @json_decode($pddToken['extends'],true);
            //推送菜鸟失败的情况下，立即返回
            $resCaiNiao = $this->callSdkApi(ShopPddOrderSendCaiNiaoSupplierApiClient::class,$param['apiBody'])->createOrder($param);
            if( $resCaiNiao['code'] != Normal::SUC ) {
                return $resCaiNiao;
            }

            $orderItem      = $param['orderGoods'];
            $supplierOrder  = $param['supplierOrder'];

            $wareHouseParam = WarehouseInfo::instance()->info(['ID'=>$supplierOrder['store_id']]);
            if( empty($wareHouseParam['JsonBody']) ) {
                return Normal::returnCode(Normal::FAIL,"仓库参数JsonBody不能为空");
            }
            $apiBody = @json_decode($wareHouseParam['JsonBody'],true);
            if( empty($apiBody['customerSupplierCode']) ) {
                return Normal::returnCode(Normal::FAIL,"仓库参数customerSupplierCode不能为空");
            }

            // 获取指定供应商商品数据
            $allSupplierSkuCodes = array_column($orderItem,'supplier_skucode');
            $listSupplierCodes   = $this->getOtherSupplierGoodsBySupplierCodeAndSkuCodes($apiBody['customerSupplierCode'],$allSupplierSkuCodes);
            if( empty($listSupplierCodes) ) {
                return Normal::returnCode(Normal::FAIL,"菜鸟业务『未找到关联供应商『{$wareHouseParam['ParameterValue']}】商品批次数据，请联系管理员和对！』");
            }

            //菜鸟推送成功之后，再推送给关务创建订单接口
            $param['listSupplierCodes'] = $listSupplierCodes;
            $resGwCreateOrder = $this->callSdkApi(ShopPddUserSpecialGwApiClient::class,$apiBody)->createOrder($param);
            if( $resGwCreateOrder['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"拼多多菜鸟仓订单推送关务仓订单创建失败【{$resGwCreateOrder['msg']}】");
            }

            //推送关务支付接口
            $resGwPayOrder = $this->callSdkApi(ShopPddUserSpecialGwApiClient::class,$apiBody)->payOrder($param);
            if( $resGwPayOrder['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"拼多多菜鸟仓订单推送关务仓订单支付确认接口操作失败【{$resGwPayOrder['msg']}】");
            }

            //返回菜鸟供应商响应报文
            return $resCaiNiao;
        } else {
            return $this->callSdkApi(ShopCaiNiaoApiClient::class,$param['apiBody'])->createOrder($param);
        }
    }

    /*
     * 获取指定供应商商品数据
     */
    public function getOtherSupplierGoodsBySupplierCodeAndSkuCodes( string $supplierCode, array $skuCodes = [] )
    {
        $alias_stock_table = SupplierCompany::instance()->getTable();
        $list = SupplierCompany::instance()
        ->from($alias_stock_table." as s")
        ->select([
            "stock.BatchID",
            "scb.SupplierCommoditySkuCode"
        ])
        ->join("suppliercommodity_s2b as scb","scb.SupplierCompanyID","=","s.ID")
        ->join("stockinfo_s2b as stock",function($join){
            $join->on("stock.SupplierCommodityID","=","scb.ID")
            ->on("stock.SupplierCompanyID","=","s.ID");
        })
        ->where('s.SupplierCode',$supplierCode)
        ->whereIn('scb.SupplierCommoditySkuCode',$skuCodes)
        ->get()
        ->toArray();
        return array_column($list,'BatchID','SupplierCommoditySkuCode');//随机抽一个批次
    }

    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }

    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale( $param = [] )
    {
        $binfo = $param['binfo'];
        if( $binfo['user_tag'] == self::PDD_USER_TAG ) {//拼多多专用
            //取消关务
            $this->callSdkApi(ShopPddUserSpecialGwApiClient::class,$param['apiBody'])->cancelOrder($param);
            //取消菜鸟
            return $this->callSdkApi(ShopPddOrderSendCaiNiaoSupplierApiClient::class,$param['apiBody'])->cancelOrder($param);
        } else {
            return $this->callSdkApi(ShopCaiNiaoApiClient::class,$param['apiBody'])->cancelOrder($param);
        }
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function orderExpress( $param = [] )
    {
        $supplierExpress = $this->callSdkApi(ShopCaiNiaoApiClient::class,$param['apiBody'])->queryOrder([
            'orderSnLists' => [$param['supplier_dsn']]
        ]);
        if( $supplierExpress['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$supplierExpress['msg']);
        }

        if( empty($supplierExpress['data']) ) {
            return Normal::returnCode(Normal::FAIL,"还未发货");
        }

        sleep(1);
        $ships = current($supplierExpress['data'])['Packages'];

        $ExpressName = implode(",", array_column($ships,'ExpressName'));
        $TrackingNo  = implode(",", array_column($ships,'TrackingNo'));
        return  Normal::returnCode(Normal::SUC,"已发货",[
            'expressInfo' => [
                'express_name'  => $ExpressName,
                'express_sn'    => $TrackingNo,
            ]
        ]);
    }

    /**
     * 获取订单清关申报的报文
     * @return mixed
     */
    public function getOrderClearanceApplyConents( $param = [] )
    {
        $orderList  = $param['orderList'];
        $orderGoods = $param['orderGoods'];
        $supplier   = $param['supplier'];
        $contents = [];
        foreach ($orderList as $orderItem )
        {
            $res = $this->callSdkApi(ShopPddOrderSendCaiNiaoSupplierApiClient::class,$param['apiBody'])->queryOrderDeclare([
                'supplierOrder' => $orderItem,
                'orderGoods'    => $orderGoods[$orderItem['order_id']],
                'supplier'      => $supplier
            ]);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }
            $contents[] = $res['data'];
        }
        return Normal::returnCode(Normal::SUC,"获取当前供应商订单申报报文成功",$contents);
    }

    /**
     * 获取每个供应商接口响应报文
     * @param array $response
     */
    public function getResponseCode( $response = [] ,$request = [] )
    {
        $res = $response['result'];
        $resHttp = @json_decode($res, true);
        if( empty($resHttp) ) {
            $resHttp = json_decode(json_encode(simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        }

        $errorMsg = $resHttp['errorMsg']??'请求失败';
        if( isset($resHttp['success']) && $resHttp['success'] == 'true' ) {

            //获取菜鸟清关单号成功之后向龙南关务推送清单号
            $copInfo = @json_decode($resHttp['data'],true);
            if( !empty($copInfo['copNo']) ) {
                $updateData = [
                    'supplierOrder' => [
                        'copNo'     => $copInfo['copNo'],
                        'order_sn'  => $request['uid']
                    ],
                    'supplier'  => [
                        'company_code'  => 'shopcainiao'
                    ]
                ];

                $res = $this->callSdkApi(ShopPddUserSpecialGwApiClient::class,$param['apiBody'])->copcodeUpdate($updateData);
                if( $res['code'] != Normal::SUC ) {
                    return Normal::returnCode(Normal::FAIL,"关务清关订单号更新失败【{$res['msg']}】",[
                        'orderDeclareContents'  => ''
                    ]);
                }

                return Normal::returnCode(Normal::SUC,"获取清关报文成功",[
                    'orderDeclareContents'  => $resHttp['data']
                ]);
            } else {
                return Normal::returnCode(Normal::FAIL,"菜鸟报文解析错误",[
                    'orderDeclareContents'  => ''
                ]);
            }
        }
        return Normal::returnCode(Normal::FAIL,$errorMsg,[
            'orderDeclareContents' => ''
        ]);
    }

    /**
     * 商品列表查询接口
     * @param array $param
     * @return mixed
     */
    public function queryGoodsList( $param = [] )
    {
        /**
         *  这里需要判断类型
         *  type 1=更新库存 2=拉商品 3=无操作
         *  mode 1=直连 2=菜园
         */
        $type=$param['apiBody']['type']??3;
        $mode=$param['apiBody']['mode']??1;
        if ($type==3){
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'total' =>  0,
                'list'  =>  []
            ]);        
        }
        //判断菜鸟的模式
        $res = $this->callSdkApi(ShopCaiNiaoApiClient::class,$param['apiBody'])->{__FUNCTION__}($param['queryBody']);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $list=$res['data']['itemList']['item']??[];
//        $list=$res['data']['batchInventoryList']['batchInventory']??[];
        //判断是否更新库存模式
        if (empty($list)){
            $is_end=true;
        }else{
            $is_end=false;
        }
        //菜园模式
        if ($mode==2){
            //查询该供应商的商品
            $newList=[];
            if ($list){
                $mapData=SupplierCommodity::instance()->getKeyAndBarCode($param['queryBody']['supplierID']);
                $itemCodeMap=array_column($list,NULL,'itemId');
                $barCodeMap=array_column($list,NULL,'barCode');
                foreach ($mapData as $mapDatum){
                    if (isset($itemCodeMap[$mapDatum['SupplierCommodityKey']])){
                        $itemCodeMap[$mapDatum['SupplierCommodityKey']]['itemId']=$mapDatum['SupplierCommoditySkuCode'];
                        $newList[]=$itemCodeMap[$mapDatum['SupplierCommodityKey']];
                    }
                    elseif (isset($barCodeMap[$mapDatum['SupplierCommodityInternationBarCode']])){
                        $barCodeMap[$mapDatum['SupplierCommodityInternationBarCode']]['itemId']=$mapDatum['SupplierCommoditySkuCode'];
                        $newList[]=$barCodeMap[$mapDatum['SupplierCommodityInternationBarCode']];
                    }
                }
                $list=$newList;
            }
        }
        
        
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'total' => $res['data']['totalCount'] ?? 0,
            'list'  => $list,
            'is_end'=> $is_end
        ]);
    }
}